{{-- resources/views/lottery.blade.php --}}
    <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>彩票号码展示</title>
    <style>
        body {
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
            display: flex;
            flex-direction: row;
        }

        .table-wrapper {
            position: relative;
            width: calc(100% - 250px);
            max-width: 800px;
            margin-left: 20px;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            background-color: #fff;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            overflow: hidden;
            margin-bottom: 20px;
            position: relative;
            z-index: 1;
        }

        thead th {
            background-color: #333;
            color: #fff;
            padding: 12px 0;
            font-size: 16px;
        }

        tbody td {
            text-align: center;
            padding: 12px 0;
            font-size: 16px;
        }

        .number-row {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        .number-ball {
            display: inline-block;
            width: 32px;
            height: 32px;
            line-height: 32px;
            margin: 2px 8px;
            border-radius: 50%;
            background-color: #ff4d4f;
            color: #fff;
            font-weight: bold;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            position: relative;
            z-index: 3;
        }

        .hit {
            background-color: #1890ff !important;
        }

        .predict-ball {
            background-color: #52c41a !important;
        }

        .predict-row {
            background-color: #fff8e1;
        }

        td.period {
            background-color: #333;
            color: #fff;
            font-weight: bold;
        }

        #connection-lines {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 2;
            overflow: visible;
        }

        .pagination {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
        }

        .pagination a {
            padding: 6px 12px;
            text-decoration: none;
            border: 1px solid #ccc;
            border-radius: 4px;
            color: #333;
            transition: all 0.2s;
        }

        .pagination .disabled {
            pointer-events: none;
            color: #aaa;
            border-color: #eee;
        }

        .pagination .info {
            margin-right: 10px;
        }

        .feature-buttons {
            display: flex;
            gap: 10px;
            margin-top: 10px;
            margin-bottom: 40px;
        }

        .feature-buttons button {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            background-color: #1890ff;
            color: #fff;
            font-size: 14px;
            cursor: pointer;
        }

        .feature-buttons button:hover {
            background-color: #40a9ff;
        }

        .scroll-buttons {
            position: fixed;
            right: 20px;
            bottom: 100px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            z-index: 999;
        }

        .scroll-buttons button {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            border: none;
            background-color: #1890ff;
            color: #fff;
            font-size: 18px;
            cursor: pointer;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
            transition: background-color 0.2s;
        }

        .scroll-buttons button:hover {
            background-color: #40a9ff;
        }

        .sidebar {
            width: 220px;
            background-color: #fff;
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            max-height: 90vh;
            overflow-y: auto;
        }

        .sidebar h3 {
            margin-top: 0;
            font-size: 16px;
            margin-bottom: 10px;
        }

        .sidebar ul {
            list-style: none;
            padding-left: 0;
            margin: 0;
        }

        .sidebar li {
            padding: 6px 8px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background 0.2s;
        }

        .sidebar li:hover {
            background-color: #f0f0f0;
        }

        @media (max-width: 800px) {
            body {
                flex-direction: column;
            }

            .table-wrapper {
                width: 100%;
                margin-left: 0;
            }

            .sidebar {
                width: 100%;
                max-height: none;
                margin-bottom: 20px;
            }
        }
    </style>
</head>
<body>

<div class="sidebar">
    <h3>符合规律的数据有 {{ $data['hit_count'] }} 条</h3>
    <ul>
        @foreach($data['hit_list'] as $index => $item)
            <li onclick="loadData({{ $index }})">
                [连续{{$item['max_consecutive']}}次] {{ $item['path_string'] }}
            </li>
        @endforeach
    </ul>
</div>

<div class="table-wrapper" id="table-wrapper">
    <svg id="connection-lines" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"></svg>

    <table>
        <thead>
        <tr>
            <th>期号</th>
            <th>号码</th>
            <th>是否预测</th>
        </tr>
        </thead>
        <tbody id="table-body">
        {{-- 初始不渲染任何数据 --}}
        <tr>
            <td colspan="3">请选择左侧数据进行展示</td>
        </tr>
        </tbody>
    </table>

    <div class="pagination" id="pagination">
        <span class="info">总 0 条，当前 0 / 0 页</span>
        <a href="javascript:;" id="prevPage">上一页</a>
        <a href="javascript:;" id="nextPage">下一页</a>
    </div>

</div>

<div class="scroll-buttons">
    <button onclick="window.scrollTo({top: 0, behavior: 'smooth'})" title="返回顶部">↑</button>
    <button onclick="window.scrollTo({top: document.body.scrollHeight, behavior: 'smooth'})" title="去底部">↓</button>
</div>

<script>
    let lotteryData = @json($data['hit_list']);
    let selectedIndex = null;      // 当前选中的 hit_list 下标
    let currentItems = [];
    let currentPage = 1;
    let perPage = 20;
    let totalPages = 1;
    const urlParams = new URLSearchParams(window.location.search);
    const type = parseInt(urlParams.get('type')) || 1;

    // 点击左侧列表
    function loadData(index) {
        selectedIndex = index;
        const hit = lotteryData[index];
        currentPage = 1;
        perPage = 20; // 可根据实际后端分页参数调整
        totalPages = Math.ceil(Object.keys(hit.items).length / perPage);
        updateCurrentItems();
        renderTable();
        drawLotteryConnections();
    }

    function updateCurrentItems() {
        if (selectedIndex === null) return;
        const hit = lotteryData[selectedIndex];

        // 倒序期号数组
        const keys = Object.keys(hit.items).sort((a, b) => b - a);

        const start = (currentPage - 1) * perPage;
        const end = start + perPage;
        const pageKeys = keys.slice(start, end);

        // 翻转当前页，使页内从早到晚显示
        pageKeys.reverse();

        // 构造当前页数据
        currentItems = pageKeys.map(k => {
            const item = hit.items[k];
            return {
                ...item,
                periods: k
            };
        });

        totalPages = Math.ceil(keys.length / perPage);

        if (currentPage === 1) {
            // 增加待开奖占位数据
            const maxKey = Math.max(...keys.map(Number));
            currentItems.push({
                periods: maxKey + 1, // 待开奖期号
                origin: [],          // 空数组
                hit: [],             // 空数组
                is_predict: true     // 标记为预测行
            });
        }
    }


    // 分页操作
    document.getElementById('prevPage').addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            updateCurrentItems();
            renderTable();
            drawLotteryConnections();
        }
    });
    document.getElementById('nextPage').addEventListener('click', () => {
        if (currentPage < totalPages) {
            currentPage++;
            updateCurrentItems();
            renderTable();
            drawLotteryConnections();
        }
    });

    // 渲染表格
    function renderTable() {
        const tbody = document.getElementById('table-body');
        tbody.innerHTML = '';
        if (currentItems.length === 0) {
            tbody.innerHTML = '<tr><td colspan="3">没有数据</td></tr>';
            document.querySelector('#pagination .info').textContent = '总 0 条，当前 0 / 0 页';
            return;
        }

        currentItems.forEach(item => {
            const tr = document.createElement('tr');
            tr.className = item.is_predict ? 'predict-row' : '';
            tr.id = 'row-' + item.periods;

            let tdPeriod = document.createElement('td');
            tdPeriod.className = 'period';
            tdPeriod.textContent = item.periods;

            let tdNumbers = document.createElement('td');
            const numberDiv = document.createElement('div');
            numberDiv.className = 'number-row';
            item.origin.forEach((num, idx) => {
                const span = document.createElement('span');
                span.className = 'number-ball';

                // 命中高亮
                if (item.hit && item.hit.includes(idx + 1)) span.classList.add('hit');

                // 根据当前查询参数 type 控制预测球颜色
                if (item.is_predict) {
                    if (type == 3 && (idx === 0 || idx === 1)) {
                        span.classList.add('predict-ball');
                    }
                    if (type == 4 && (idx === 0 || idx === 2)) {
                        span.classList.add('predict-ball');
                    }
                    if (type == 5 && (idx === 1 || idx === 2)) {
                        span.classList.add('predict-ball');
                    }
                }

                span.dataset.period = item.periods;
                span.dataset.index = idx + 1;
                span.textContent = num;
                numberDiv.appendChild(span);
            });

            tdNumbers.appendChild(numberDiv);

            let tdPredict = document.createElement('td');
            tdPredict.textContent = item.is_predict ? '是' : '否';

            tr.appendChild(tdPeriod);
            tr.appendChild(tdNumbers);
            tr.appendChild(tdPredict);
            tbody.appendChild(tr);
        });

        document.querySelector('#pagination .info').textContent =
            `总 ${Object.keys(lotteryData[selectedIndex].items).length} 条，当前 ${currentPage} / ${totalPages} 页`;

        // 更新分页按钮状态
        document.getElementById('prevPage').classList.toggle('disabled', currentPage <= 1);
        document.getElementById('nextPage').classList.toggle('disabled', currentPage >= totalPages);
    }

    (function () {
        const wrapper = document.getElementById('table-wrapper');
        const svg = document.getElementById('connection-lines');

        function clearSvg() {
            while (svg.firstChild) svg.removeChild(svg.firstChild);
        }

        function resizeSvgToWrapper() {
            const r = wrapper.getBoundingClientRect();
            svg.setAttribute('width', r.width);
            svg.setAttribute('height', r.height);
            svg.style.width = r.width + 'px';
            svg.style.height = r.height + 'px';
            svg.setAttribute('viewBox', `0 0 ${r.width} ${r.height}`);
        }

        function getCenterRelativeToWrapper(el, wrapperRect) {
            const rect = el.getBoundingClientRect();
            const x = rect.left - wrapperRect.left + rect.width / 2;
            const y = rect.top - wrapperRect.top + rect.height / 2;
            return {x, y};
        }

        function drawLines() {
            clearSvg();
            resizeSvgToWrapper();
            const wrapperRect = wrapper.getBoundingClientRect();
            const rows = Array.from(document.querySelectorAll("tbody tr"));
            let currentGroup = [];

            function drawGroup(group) {
                if (group.length < 2) return;
                const radius = 16;
                for (let i = 0; i < group.length - 1; i++) {
                    const p1 = group[i], p2 = group[i + 1];
                    const dx = p2.x - p1.x, dy = p2.y - p1.y, dist = Math.sqrt(dx * dx + dy * dy);
                    if (dist < 1) continue;
                    const offsetX = (dx / dist) * radius, offsetY = (dy / dist) * radius;
                    const x1 = p1.x + offsetX, y1 = p1.y + offsetY, x2 = p2.x - offsetX, y2 = p2.y - offsetY;
                    const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
                    line.setAttribute("x1", x1);
                    line.setAttribute("y1", y1);
                    line.setAttribute("x2", x2);
                    line.setAttribute("y2", y2);
                    line.setAttribute("stroke", "#1890ff");
                    line.setAttribute("stroke-width", "2");
                    line.setAttribute("stroke-linecap", "round");
                    svg.appendChild(line);
                }
            }

            rows.forEach((row, rowIndex) => {
                const balls = row.querySelectorAll(".number-ball");
                const hits = row.querySelectorAll(".number-ball.hit");

                hits.forEach(ball => currentGroup.push(getCenterRelativeToWrapper(ball, wrapperRect)));

                const isPredict = row.classList.contains("predict-row");
                const isLastRow = rowIndex === rows.length - 1;

                // 遇到 predict-row 或最后一行，绘制当前连接
                if (isPredict || isLastRow) {
                    drawGroup(currentGroup);
                    currentGroup = [];

                    if (balls.length > 0 && isPredict) {
                        const centers = Array.from(balls).map(b => getCenterRelativeToWrapper(b, wrapperRect));
                        const minX = Math.min(...centers.map(c => c.x));
                        const maxX = Math.max(...centers.map(c => c.x));
                        const minY = Math.min(...centers.map(c => c.y));
                        const maxY = Math.max(...centers.map(c => c.y));

                        const ellipse = document.createElementNS("http://www.w3.org/2000/svg", "ellipse");
                        ellipse.setAttribute("cx", (minX + maxX) / 2);
                        ellipse.setAttribute("cy", (minY + maxY) / 2);
                        ellipse.setAttribute("rx", (maxX - minX) / 2 + 20);
                        ellipse.setAttribute("ry", (maxY - minY) / 2 + 20);
                        ellipse.setAttribute("stroke", "#52c41a");
                        ellipse.setAttribute("stroke-width", "3");
                        ellipse.setAttribute("fill", "none");
                        ellipse.setAttribute("stroke-dasharray", "6,4");
                        svg.appendChild(ellipse);
                    }
                }
            });
        }

        function scheduleDraw() {
            setTimeout(drawLines, 30);
        }

        document.addEventListener('DOMContentLoaded', scheduleDraw);
        window.addEventListener('load', scheduleDraw);
        window.addEventListener('resize', scheduleDraw);
        window.drawLotteryConnections = scheduleDraw;
    })();
</script>
</body>
</html>
